package com.qf.service;

import com.qf.utils.ConnectionUtils;
import com.sun.xml.internal.ws.server.ServerRtException;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.security.CreateApiKeyRequest;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.json.JsonXContent;


import java.io.IOException;

public class IndexServiceImpl implements IndexService{
    @Override
    public void createIndex(String index) throws IOException {
        RestHighLevelClient highLevelClient = ConnectionUtils.getClient();
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(index); //创建库的请求对象,参数是库的名字
        createIndexRequest.settings(Settings.builder().put("number_of_shards",5)//设置数据会被拆分成5份
                .put("number_of_replicas",1).build());//每一份还有一个备份数据
//json只有两种格式,一种是object,一种是array {}开头的就是一个对象 []就是一个数组,两个可以嵌套
        XContentBuilder xContentBuilder = JsonXContent.contentBuilder().startObject()
                .startObject("properties")
                .startObject("name").field("type", "text").field("analyzer", "ik_max_word")
                .endObject().startObject("count").field("type", "long").endObject()
                .startObject("on-sale").field("type", "date").field("format", "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis").endObject()
                .startObject("descr").field("type", "text").field("analyzer", "ik_max_word").endObject()
                .endObject().endObject();
        createIndexRequest.mapping(xContentBuilder);  //设置列的信息

        CreateIndexResponse response = highLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);//和库相关的的操作
        System.err.println(response);

    }
}
